package com.zhitxx.common.utils

import com.tencent.mmkv.MMKV
import com.tencent.mmkv.MMKV.initialize

/**
 * MMKV 工具类
 */
object SPUtils {
    var mmkv: MMKV? = null


    init {
        mmkv = MMKV.defaultMMKV()
    }
    @JvmStatic
    fun init() {
        initialize(AppUtils.getContexts())
    }

    /**
     * 初始化MMKV
     */
    @JvmStatic
    fun save(key: String, value: Any) {
        when (value) {
            is String -> mmkv?.encode(key, value)
            is Float -> mmkv?.encode(key, value)
            is Boolean -> mmkv?.encode(key, value)
            is Int -> mmkv?.encode(key, value)
            is Long -> mmkv?.encode(key, value)
            is Double -> mmkv?.encode(key, value)
            is ByteArray -> mmkv?.encode(key, value)
            is Nothing -> return
        }
    }
    @JvmStatic
    fun getByteArray(key: String): ByteArray =
            mmkv!!.decodeBytes(key)

    @JvmStatic
    fun getDoubleValue(key: String, defaultValue: Double): Double =
            mmkv!!.decodeDouble(key, defaultValue)

    @JvmStatic
    fun getLongValue(key: String, defaultValue: Long): Long =
            mmkv!!.decodeLong(key, defaultValue)

    @JvmStatic
    fun getIntValue(key: String, defaultValue: Int): Int =
            mmkv!!.decodeInt(key, defaultValue)

    @JvmStatic
    fun getBooleanValue(key: String, defaultValue: Boolean): Boolean =
            mmkv!!.decodeBool(key, defaultValue)

    @JvmStatic
    fun getFloatValue(key: String, defaultValue: Float) {
        mmkv!!.decodeFloat(key, defaultValue)
    }
    @JvmStatic
    fun getStringValue(key: String): String =
            getStringValue(key, "")

    @JvmStatic
    fun getStringValue(key: String, defaultValue: String): String =
            mmkv!!.decodeString(key, defaultValue)
    @JvmStatic
    fun clearValueByKey(key: String) {
        mmkv!!.removeValueForKey(key)
    }
    @JvmStatic
    fun clearValueByKeys(keys: Array<String>) {
        mmkv!!.removeValuesForKeys(keys)
    }

    @JvmStatic
    fun clearAll() {
        mmkv!!.clearAll()
    }

}